package com.bawei.week3.fragment;


import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import com.bawei.week3.MainActivity;
import com.bawei.week3.R;

import androidx.fragment.app.Fragment;

/**
 * A simple {@link Fragment} subclass.
 */
public class MessageFragment extends Fragment {
    private MyRecevicer myRecevicer;



    public MessageFragment() {
        // Required empty public constructor
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        //注册
        myRecevicer = new MyRecevicer();
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction("com.bawei.music");
       // intentFilter.setPriority(600);//设置优先级
        getActivity().registerReceiver(myRecevicer,intentFilter);

        return inflater.inflate(R.layout.fragment_music, container, false);
    }

    //解除注册
    @Override
    public void onDestroyView() {
        super.onDestroyView();
        getActivity().unregisterReceiver(myRecevicer);
    }

    class MyRecevicer extends BroadcastReceiver{

        @Override
        public void onReceive(Context context, Intent intent) {
            if("com.bawei.music".equals(intent.getAction())){
                Bundle bundle = intent.getExtras();
                String name = bundle.getString("name");
               //发送一个通知
                NotificationManager manager = (NotificationManager) getActivity().getSystemService(Context.NOTIFICATION_SERVICE);
                Notification.Builder builder = new Notification.Builder(getContext());
                builder.setSmallIcon(R.mipmap.ic_launcher);
                builder.setContentText(name);
                //点击通知回到页面
                Intent intent1 = new Intent(getActivity(), MainActivity.class);
                PendingIntent pendingIntent = PendingIntent.getActivity(getContext(), 101, intent1, PendingIntent.FLAG_ONE_SHOT);
                builder.setContentIntent(pendingIntent);


                manager.notify(1,builder.build());

            }
        }
    }

}
